<template>
  <div>
    <my-breadcrumb :items="['社区管理', '话题管理']"/>
    <search :formItems="searchItems" @search="getList" ref="search"/>
    <div class="add">
      <el-button type="primary" @click="toAdd">新增话题</el-button>
    </div>
    <el-table :data="topics" @sort-change="orderByTime">
      <el-table-column
        type="index"
        width="55">
      </el-table-column>
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        label="创建时间"
        sortable="custom"
        prop="createtime">
      </el-table-column>
      <el-table-column
        label="话题名称"
        prop="title">
      </el-table-column>
      <el-table-column
        label="话题分类"
        prop="classify">
      </el-table-column>
      <el-table-column
        label="关注人数"
        sortable="custom"
        width="110px"
        prop="number">
      </el-table-column>
      <el-table-column
        label="发帖量"
        sortable="custom"
        width="90px"
        prop="articlecount">
      </el-table-column>
      <el-table-column
        label="话题图片"
        prop="img">
        <template slot-scope="scope">
          <img v-if="scope.row.img" :src="scope.row.img" alt="" width="40px" height="40px">
        </template>
      </el-table-column>
      <el-table-column
        label="是否热门"
        prop="isrecommend">
        <template slot-scope="scope">
          <span>{{ scope.row.isrecommend === '1' ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        prop="id">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="toUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="toDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>
    <el-dialog :title="isAdd ? '新增话题' : '信息修改'" :visible.sync="showAdd" width="400px">
      <el-form :model="topic" :rules="rules" label-width="90px" ref="addForm">
        <el-form-item label="话题名称" prop="title">
          <el-input v-model="topic.title"/>
        </el-form-item>
        <el-form-item label="话题图片" prop="img">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="话题分类" prop="tlabelid">
          <el-select v-model="topic.tlabelid">
            <el-option v-for="(item, index) in clazz" :key="index" :value="item.id" :label="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否热门" prop="isrecommend">
          <el-select v-model="topic.isrecommend">
            <el-option value="1" label="是"/>
            <el-option value="0" label="否"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="addTopic" :loading="addLoading">{{ addLoading ? '处理中...' : '提交' }}</el-button>
        <el-button type="danger" @click="showAdd = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteRow} from '../../utils/getList'
export default {
  name: 'topic',
  data () {
    return {
      searchItems: [
        {
          label: '话题标题',
          type: 'input',
          key: 'title'
        },
        {
          label: '话题时间',
          type: 'times',
          key: 'times'
        },
        {
          label: '是否推荐',
          type: 'select',
          key: 'isrecommend',
          options: [{id: '1', name: '是'}, {id: '0', name: '否'}]
        }
      ], // 检索结构
      topics: [],
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      showAdd: false,
      isAdd: true,
      topic: {
        title: '',
        img: '',
        tlabelid: '',
        isrecommend: '1'
      },
      rules: {
        title: [
          { required: true, message: '请输入话题标题', trigger: 'blur' }
        ],
        img: [
          { required: true, message: '请输入话题图片', trigger: 'blur' }
        ],
        tlabelid: [
          { required: true, message: '请选择话题分类', trigger: 'change' }
        ]
      },
      imageUrl: '',
      addLoading: false,
      classifyList: [],
      clazz: [],
      updateRow: null,
      lifting: null
    }
  },
  methods: {
    // /Topic/index
    getList () {
      let searchData = {}
      if (this.$refs['search']) {
        searchData = this.$refs['search'].search()
      }
      let params = {...searchData, page: this.page.pageNum, size: this.page.pageSize, orderby: this.lifting}
      this.axios.get('/Topic/index', {params})
        .then(res => {
          if (res.data.status) {
            this.page.total = Number(res.data.data.count)
            res.data.data.list.forEach(item => {
              item.classify = this.classifyList['I' + item.tlabelid] ? this.classifyList['I' + item.tlabelid].value : ''
            })
            this.topics = res.data.data.list
          }
        })
    },
    handleSizeChange (e) {
      this.page.pageSize = e
      this.getList()
    },
    handleCurrentChange (e) {
      this.page.pageNum = e
      this.getList()
    },

    getClassifyList (callback) {
      this.axios.get('/type/gettopiclabel')
        .then(res => {
          if (res.data.status) {
            this.clazz = res.data.data
            let options = []
            res.data.data.forEach(item => {
              this.classifyList['I' + item.id] = item
              options.push({
                id: item.id,
                name: item.value
              })
            })
            this.searchItems.push({
              label: '话题分类',
              type: 'select',
              key: 'tlabelid',
              options
            })
          }
          callback()
        })
    },

    beforeUpload (file) {
      let reader = new FileReader()
      let _self = this
      reader.onload = function (ev) {
        _self.topic.img = ev.currentTarget.result
      }
      reader.readAsDataURL(file)
      this.imageUrl = URL.createObjectURL(file)
      return false
    },

    orderByTime (lifting) {
      if (lifting.order === 'ascending') {
        this.lifting = lifting.prop + ' asc'
      } else {
        this.lifting = lifting.prop + ' desc'
      }
      this.getList()
    },

    toAdd () {
      this.isAdd = true
      this.showAdd = true
      this.imageUrl = ''
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
        this.$refs['addForm'].clearValidate()
      })
    },
    addTopic () {
      this.addLoading = true
      let url = '/Topic/add'
      let params = JSON.parse(JSON.stringify(this.topic))
      if (!this.isAdd) {
        url = '/Topic/edit'
        params.id = this.updateRow.id
      }
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.axios.post(url, this.qs.stringify(params))
            .then(res => {
              if (res.data.status === 1) {
                this.$message.success(res.data.msg)
                this.getList()
                this.showAdd = false
              }
              this.addLoading = false
            })
            .catch(() => {
              this.addLoading = false
            })
        } else {
          this.$message.error('请检查表单是否填写正确')
          this.addLoading = false
          return false
        }
      })
    },
    toUpdate (row) {
      this.isAdd = false
      this.showAdd = true
      this.$nextTick(() => {
        Object.keys(this.topic).forEach(key => {
          this.topic[key] = row[key]
        })
        this.$refs['addForm'].clearValidate()
      })
      this.imageUrl = row.img
      this.updateRow = row
    },
    toDelete (id) {
      deleteRow({url: '/Topic/delete', id}, res => {
        if (res.data.status === '1' || res.data.status === 1) {
          this.$message.success(res.data.msg)
          this.getList()
        }
      })
    }
  },
  created () {
    this.getClassifyList(this.getList)
    // this.getList()
  }
}
</script>

<style scoped>
  .add{
    margin-bottom: 16px;
  }
  .avatar-uploader-icon:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
